package com.mytrip.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil{
	private static final Log log = LogFactory.getLog(HttpUtil.class);

	public static String get(String url){
		String res = null;
		HttpClient httpClient = new DefaultHttpClient();
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity entity = httpResponse.getEntity();
			res = EntityUtils.toString(entity);
		} catch (Exception e) {
			log.warn("", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return res;
	}

	public static String post(String url, Map<String, String> params){
		String res = null;
		HttpClient httpClient = new DefaultHttpClient();
		try {
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			for (Entry<String, String> e : params.entrySet()) {
				param.add(new BasicNameValuePair(e.getKey(), e.getValue()));
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(param, "UTF-8");

			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity entity2 = httpResponse.getEntity();
			res = EntityUtils.toString(entity2, "UTF-8");
		} catch (Exception e) {
			log.warn("", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return res;
	}
}
